﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;

namespace _001.日刷.剑指OfferII
{
    public class _002二进制加法
    {
        public class Solution
        {
            public string AddBinary(string a, string b)
            {
                StringBuilder sb=new StringBuilder();

                int carry = 0;
                for (int i = a.Length-1, j = b.Length-1; i >= 0 || j >= 0; i--, j--)
                {
                    int ai = i >= 0 ? a[i] - '0' : 0;
                    int aj = j >= 0 ? b[j] - '0' : 0;
                    int p = (ai + aj+ carry) % 2;
                    carry = (ai + aj+ carry) / 2;
                    sb.Append(p);
                }

                if (carry == 1)
                {
                    sb.Append(carry);
                }
                return ReverseUsingCharArray(sb.ToString());

            }
            public static string ReverseUsingCharArray(string str)
            {
                char[] arr = str.ToCharArray();
                Array.Reverse(arr);
                return new string(arr);
            }
        }

        ITestOutputHelper output;
        public _002二进制加法(ITestOutputHelper output)
        {
            this.output = output;
        }

        [Fact]
        public void Test1()
        {
            Solution rSolution = new Solution();
            var r = rSolution.AddBinary("11", "10");
            output.WriteLine(r );
        }
    }
}
